<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="店铺名称">
                <a-input allow-clear placeholder="请输入店铺名称" v-model="queryParam.store_name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="用户昵称">
                <a-input allow-clear placeholder="请输入用户昵称" v-model="queryParam.nickname"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号码">
                <div class="select">
                  <a-input placeholder="请输入手机号码" v-model="queryParam.mobile"></a-input>
                  <a-button type="primary" @click="getList">查询</a-button>
                </div>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false" class="card_style_re">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.status" @change="getList">
          <a-radio-button value="-1"> 全部 </a-radio-button>
          <a-radio-button value="0"> 未开启 </a-radio-button>
          <a-radio-button value="1"> 已开启 </a-radio-button>
        </a-radio-group>
        <div>
        <a-button type="primary" @click="showAdd = true">+ 新建</a-button>
        <a-button type="primary" @click="toSetting(-1)">默认设置</a-button>
        </div>
      </div>
      <a-table
        :rowKey="
          (r, i) => {
            return i
          }
        "
        :pagination="{
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
        :columns="columns"
        :data-source="list"
        :scroll="{ x: 'max-content' }"
      >
        <div slot="name" slot-scope="text, record">
          <div class="name">
            <div class="pic">
              <img :src="record.avatar" alt="" />
            </div>
            <div class="info">
              <span>{{ record.nickname }}</span>
              <span>{{ record.mobile }}</span>
            </div>
          </div>
        </div>
        <div slot="referral_rebate" slot-scope="scope, record">
          <div class="referral_rebate">
            <span>{{ record.referral_rebate }}%</span>
             <span v-if="record.use_default" style="color:#65c817"><br>系统默认值</span>
          </div>
        </div>
        <div slot="status" slot-scope="scope">
          <div class="status">
            <span :class="scope == 0 ? 'disabled' : 'open'"></span>
            <span>{{ scope == 0 ? '未开启' : '已开启' }}</span>
          </div>
        </div>
        <span slot="amount" slot-scope="text"> ￥{{ text || 0 }} </span>
        <span slot="action" slot-scope="scope">
          <a-button type="link" size="small" @click="toSetting(scope)">设置</a-button>
          <a-divider type="vertical" style="margin:0 1px;"/>
          <a-dropdown>
            <a-button type="link" size="small"> 更多 <a-icon type="down" /></a-button>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm title="确认关闭吗？" :disabled="scope.is_enable == 0" @confirm="changeStatus(scope, '0')">
                  <a-button type="link" size="small" :disabled="scope.is_enable == 0">关闭</a-button>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确认开启吗？" :disabled="scope.is_enable == 1" @confirm="changeStatus(scope, '1')">
                  <a-button type="link" size="small" :disabled="scope.is_enable == 1">开启</a-button>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确认删除吗？" @confirm="delRecord(scope)">
                  <a-button type="link" size="small">删除</a-button>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </a-card>
    <!-- 设置弹窗 -->
    <a-modal
      title="店铺推荐人设置"
      width="800px"
      v-model="showAdd"
      @ok="editSetting"
      :confirmLoading="btnLoading"
      :destroyOnClose="true"
      :afterClose="closeModal"
    >
      <a-form-model
        ref="settingForm"
        :model="settingForm"
        :rules="settingRules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-model-item label="是否开启" prop="is_enable">
          <a-radio-group v-model="settingForm.is_enable">
            <a-radio value="1"> 开启 </a-radio>
            <a-radio value="0"> 关闭 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="返佣比例" prop="referral_rebate">
          <a-input addon-after="%" placeholder="请输入返佣比例" v-model="settingForm.referral_rebate" />
        </a-form-model-item>
        <a-form-model-item label="绑定用户" prop="referral_id" v-if="!settingForm.id">
          <div style="display: flex">
            <a-input v-model="referral_name" disabled />
            <a-button type="primary" @click="visible = true" style="margin-left: 15px">选择</a-button>
          </div>
        </a-form-model-item>
        <a-form-model-item label="绑定商城" prop="store_id" v-if="!settingForm.id">
          <div style="display: flex">
            <a-input v-model="store_name" disabled />
            <a-button type="primary" @click="showShop = true" style="margin-left: 15px">选择</a-button>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 选择用户弹窗 -->
    <a-modal title="选择用户" style="width: 300px" v-model="visible" :destroyOnClose="true" :footer="null">
      <div style="margin-bottom: 10px">
        <a-input-search
          placeholder="输入昵称搜索"
          v-model="keyword"
          allowClear
          enter-button
          @search="$refs.table1.refresh(true)"
        />
      </div>
      <s-table ref="table1" rowKey="id" :columns="userColumns" :data="loadUserData">
        <span slot="baseinfo" slot-scope="text, record">
          <img style="width: 40px; heigth: 40px; border-radius: 3px; margin-right: 5px" :src="record.avatar" />
          <span :length="20" tooltip>{{ record.name }}</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="primary" size="small" @click="onSelect(record, 'user')"> 选择 </a-button>
        </span>
        <span slot="status" slot-scope="scope">
          <div class="status">
            <span :class="scope.is_disable == 0 ? 'open' : 'close'"></span>
            <span>{{ scope.is_disable == 0 ? '已启用' : '已禁用' }}</span>
          </div>
        </span>
      </s-table>
    </a-modal>
    <!-- 选择商城弹窗 -->
    <a-modal title="选择商城" style="width: 300px" v-model="showShop" :destroyOnClose="true" :footer="null">
      <div style="margin-bottom: 10px">
        <a-input-search
          placeholder="输入商城名称"
          v-model="shopQuery.name"
          allowClear
          enter-button
          @search="$refs.table2.refresh(true)"
        />
      </div>
      <s-table ref="table2" rowKey="id" :columns="shopColumns" :data="loadShopData">
        <span slot="baseinfo" slot-scope="text, record">
          <img style="width: 40px; heigth: 40px; border-radius: 3px; margin-right: 5px" :src="record.avatar" />
          <span :length="20" tooltip>{{ record.name }}</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="primary" size="small" @click="onSelect(record, 'shop')"> 选择 </a-button>
        </span>
      </s-table>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { shopReferrerList, editShopReferrer,delReferrerLog } from '@/api/saas/alliance'
import { STable } from '@/components'
import { getSelectUserList } from '@/api/user'
import { getList } from '@/api/store'
import storage from 'store'
import { cyyUploadImg } from '@/components/CyyUi'
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '推荐人信息',
    scopedSlots: {
      customRender: 'name',
    },
    width: 250,
  },
  {
    title: '店铺名称',
    dataIndex: 'store_name',
  },
  {
    title: '返佣比例',
    dataIndex: 'referral_rebate',
    scopedSlots: {
      customRender: 'referral_rebate',
    },
  },
  {
    title: '累计返佣',
    dataIndex: 'amount',
    scopedSlots: {
      customRender: 'amount',
    },
  },
  {
    title: '状态',
    dataIndex: 'is_enable',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
  },
]
const userColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '用户信息',
    scopedSlots: { customRender: 'baseinfo' },
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
  },
]
const shopColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '商城名称',
    dataIndex: 'store_name',
  },
  {
    title: '类目',
    dataIndex: 'cat_name',
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

export default {
  components: {
    STable,
    cyyUploadImg,
  },
  data() {
    return {
      keyword: '',
      // 搜索参数
      queryParam: {
        page: 1,
        mobile: '',
        status: '-1',
        nickname: '',
        store_name: '',
      },
      columns,
      userColumns,
      shopColumns,
      list: [],
      // 是否显示设置分销弹窗
      showAdd: false,
      // 新增 编辑推荐人的表单
      settingForm: {
        id: '',
        store_id: '',
        referral_id: '',
        referral_rebate: '',
        is_enable: '1',
      },
      settingRules: {
        store_id: [{ required: true, message: '请选择商城', trigger: 'change' }],
        referral_id: [{ required: true, message: '请选择推荐人', trigger: 'change' }],
        referral_rebate: [{ required: true, message: '请输入返佣比例', trigger: 'blur' }],
        is_enable: [{ required: true, message: '请选择是否开启', trigger: 'change' }],
      },
      btnLoading: false,
      loadUserData: (parameter) => {
        return getSelectUserList({
          ...parameter,
          storeId: storage.get('storeId'),
          type: 'user',
          keyword: this.keyword,
        }).then((res) => {
          return res.data
        })
      },
      // 是否显示选择用户
      visible: false,
      // 是否显示选择商城
      showShop: false,
      // 查询商城参数
      shopQuery: {
        name: '',
        id: '',
        user_name: '',
        category_id: '-1',
        status: '-1',
      },
      // 加载商城数据
      loadShopData: (parameter) => {
        let { shopQuery: data } = this
        return getList({ ...parameter, ...data })
          .then((res) => {
            return res.data
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.$refs.table2.localLoading = false
          })
      },
      // 推荐人昵称
      referral_name: '',
      // 推荐的商铺的名称
      store_name: '',
      defaultSet: [],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 关闭新增编辑推荐人弹窗回调
    closeModal() {
      this.settingForm.id = ''
      this.settingForm.store_id = ''
      this.settingForm.referral_id = ''
      this.settingForm.referral_rebate = ''
      this.settingForm.is_enable = '1'
      this.store_name = ''
      this.referral_name = ''
    },
    // 分页请求
    tablePageChange(e) {
      this.queryParam.page = e
      this.getList()
    },
    // 获取数据
    async getList() {
      const hide = this.$message.loading('加载中...', 1000)
      const res = await shopReferrerList(this.queryParam)
      if (res.code == 0) {
        this.list = res.data.data
        this.totalCount = res.data.totalCount
        this.defaultSet = res.data.defaultSet
      }
      hide()
    },
    // 点击设置联盟分销
    toSetting(scope) {
      if(scope === -1){
        this.settingForm.id = 99999999999999999
        this.settingForm.store_id = -1
        this.settingForm.referral_id = 99999999999999999
        this.settingForm.referral_rebate = this.defaultSet.referral_rebate
        this.settingForm.is_enable = this.defaultSet.is_enable
        this.store_name = ""
        this.referral_name = ""
        this.showAdd = true
        return;
      }
      this.settingForm.id = scope.id
      this.settingForm.store_id = scope.store_id
      this.settingForm.referral_id = scope.referral_id
      this.settingForm.referral_rebate = scope.referral_rebate
      this.settingForm.is_enable = scope.is_enable
      this.store_name = scope.store_name
      this.referral_name = scope.nickname
      this.showAdd = true
    },
    // 点击确认设置
    editSetting() {
      this.$refs['settingForm'].validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          const res = await editShopReferrer(this.settingForm)
          this.btnLoading = false
          if (res.code == 0) {
            this.showAdd = false
            this.getList()
          }
        } else {
          return false
        }
      })
    },
    onSelect(item, type) {
      console.log(item)
      if (type == 'user') {
        this.settingForm.referral_id = item.id
        this.referral_name = item.name
        this.visible = false
      }
      if (type == 'shop') {
        this.settingForm.store_id = item.id
        this.store_name = item.name
        this.showShop = false
      }
    },
    // 修改推荐人开启关闭状态
    async changeStatus(scope, type) {
      let param = { id: scope.id, is_enable: type }
      const res = await editShopReferrer(param)
      if (res.code == 0) {
        this.showAdd = false
        this.getList()
        this.$message.success('操作成功')
      }
    },
    // 点击删除记录
    async delRecord(scope) {
      const res = await delReferrerLog({id:scope.id})
      if(res.code == 0) {
        this.getList()
        this.$message.success('操作成功')
      }
    } 
  },
}
</script>
<style lang="less" scoped>
.tip {
  line-height: normal;
  margin-bottom: 0;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
.pic {
  width: 48px;
  min-width: 48px;
  height: 48px;
  border-radius: 4px;
}
.status {
  display: flex;
  align-items: center;
  span:nth-child(1) {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 4px;
  }
  .close {
    background-color: #ff4400;
  }
  .disabled {
    background-color: #ccc;
  }
  .open {
    background-color: #65c817;
  }
}
</style>
